import numpy
import sys
import re

def calc_total_score(scores: list[float]):
    scale_factor = numpy.array([1, 10000, 1, 1, 1, 1, 1, 1, 1])
    reference_score = numpy.array([40.3438, 2855, 38.5624, 0.87959, 1.45853, 4.81116, 99.6587, 48.5201, 21.3618])
    res = (scores / reference_score * scale_factor)

    # 几何平均数
    log_data = numpy.log(res)
    geometric_mean = numpy.exp(numpy.mean(log_data)) * 1000

    return geometric_mean

if len(sys.argv) < 2:
    print("Usage: python result_stat.py <result_file>")
    sys.exit(1)

result_file = sys.argv[1]
scores : dict[int, dict[str, float]] = {}

with open(result_file, 'r') as f:
    context_count = 0
    restr = r'[ :=]+'
    for line in f:
        if line.count('contexts=') == 1:
            # -- zip-test:contexts=4
            parts = re.split(restr, line)
            context_count = int(parts[-1])
            if context_count not in scores:
                scores[context_count] = {}
        elif line.count('workloads/sec') == 1:
            # -- zip-test:workloads/sec= 55.5556
            parts = re.split(restr, line)
            test_case = parts[1]
            score = float(parts[-1])
            scores[context_count][test_case] = score

# 1 context时的总分
scores_1_context = []
test_cases = ['cjpeg-rose7-preset', 'core', 'linear_alg-mid-100x100-sp', 'loops-all-mid-10k-sp', 'nnet_test', 
              'parser-125k', 'radix2-big-64k', 'sha-test', 'zip-test']
for test_case in test_cases:
    scores_1_context.append(scores[1][test_case])
total_score_1_context = calc_total_score(scores_1_context)

for context_count in scores:
    print(f'{"RESULTS FOR " + str(context_count) + " CONTEXTS"}')
    print('                                                 MultiCore SingleCore           ')
    print('Workload Name                                     (iter/s)   (iter/s)    Scaling')
    print('----------------------------------------------- ---------- ---------- ----------')
    for test_case in scores[context_count]:
        score = scores[context_count][test_case]
        score_1_context = scores[1][test_case]
        print(f'{test_case:<45} {score:>10.2f} {score_1_context:>10.2f} {score/score_1_context:>10.2f}')
    print('')
    print(f'{"MARK RESULTS TABLE":>80}\n')
    print('Mark Name                                        MultiCore SingleCore    Scaling')
    print('----------------------------------------------- ---------- ---------- ----------')
    scores_cur_context = []
    for test_case in scores[context_count]:
        scores_cur_context.append(scores[context_count][test_case])
    total_score_cur_context = calc_total_score(scores_cur_context)
    print(f'CoreMark-PRO                                       {total_score_cur_context:.2f}    '
          f'{total_score_1_context:.2f}       {total_score_cur_context/total_score_1_context:.2f}')
    print('\n\n')